package rcpexample.handlers;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;

/**
 * ***************************************************************************** Copyright (c) 2011
 * Tasktop Technologies and others. All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0 which accompanies this
 * distribution, and is available at http://www.eclipse.org/legal/epl-v10.html
 *
 * <p>Contributors: Tasktop Technologies - initial API and implementation
 * *****************************************************************************
 */

import org.eclipse.core.resources.IFile;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IPerspectiveDescriptor;
//import org.eclipse.mylyn.context.core.ContextCore;
//import org.eclipse.mylyn.context.core.IInteractionContext;
//import org.eclipse.mylyn.context.core.IInteractionElement;
//import org.eclipse.mylyn.internal.modeling.ecoretools.EcoreDiagramUiBridge;
//import org.eclipse.mylyn.internal.modeling.ecoretools.EcoreGmfDomainBridge;
//import org.eclipse.mylyn.internal.modeling.ecoretools.EcoreToolsNavigatorUiBridge;
//import org.eclipse.mylyn.modeling.context.AbstractEmfContextTest;
//import org.eclipse.mylyn.modeling.ui.DiagramUiEditingMonitor;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

public class OpenHandler extends AbstractHandler {
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		List<String> files = Stream.of(new File(".").listFiles()).filter(file -> !file.isDirectory()).map(File::getName)
				.collect(Collectors.toList());

		StructuredSelection selection = new StructuredSelection(files);

		IWorkbench wb = PlatformUI.getWorkbench();
		IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
		IWorkbenchPage page = win.getActivePage();
		IPerspectiveDescriptor perspective = page.getPerspective();
        //System.out.println(perspective.getId());
        //System.out.println(perspective.getLabel());
		if (perspective!=null &&perspective.getId().equals( "SamplePerspective.perspective2")) {
			
			
			IViewPart viewPart=page.findView("org.eclipse.ui.navigator.ProjectExplorer");


			if (viewPart != null) {
				System.out.println(viewPart.getTitle());
				
				ISelectionProvider selProvider = viewPart.getSite().getSelectionProvider();
				selProvider.setSelection(selection);
			}
			

		}

		return null;

	}

}